<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\index\service;

use app\index\model\CommissionActivity;
use app\index\model\CommissionAssessment;
use app\index\model\Coupon as admin;
use app\index\model\UserCash;
use app\madmin\model\Agent;
use app\index\model\AgentApply;
use app\index\model\AgentBillTemporary;
use app\index\model\Configuration;
use app\index\model\User;
use app\index\model\view\AgentStatistics;
use app\index\model\view\AgentTeam;
use app\madmin\model\AgentGrade;
use app\madmin\model\Coupon;
use app\madmin\service\CommissionActivityService;
use app\madmin\service\CommissionAssessmentService;
use think\db\Query;
use think\Exception;
use think\facade\Db;

class AgentService
{

    private $user;
    private $agent;
    private $configuration;

    public function __construct()
    {
        global $user;
        $this->user = User::where('id', $user['id'])->find()->toArray();
        $this->configuration = Configuration::where(['type' => "agentExplain"])->value("configuration");
        $this->agent = Agent::where('user_id', $this->user['id'])
            ->where('delete_time', null)
            ->find();

        if (!empty($this->agent) && $this->agent->status == 0)
            throw new Exception("已经被禁用", HTTP_INVALID);

    }


    public function findAll(int $page, int $size, $level): array
    {

        $whereData = [];
        switch ($level) {
            case 1:
                $whereData = array('pid' => $this->agent->id);
                break;
            case 2:
                $whereData = array('ppid' => $this->agent->id);
                break;
            case 3:
                $whereData = array('pppid' => $this->agent->id);
                break;
            default :
                $list = Db::name('user')
                    ->where('pid', $this->agent->id)
                    ->where('id', 'NOT IN', function ($sql) {
                        $sql->name('agent')->field('user_id')->where('delete_time', 'NULL');
                    })
                    ->paginate(['page' => $page, 'list_rows' => $size]);
                break;
        }

        $list = $list ?? AgentTeam::where($whereData)
                ->field("id,pid,nickname,picurl,agent_total,child_agent,create_time")
                ->paginate(['page' => $page, 'list_rows' => $size]);

        return [HTTP_SUCCESS, $list];
    }

    public function read(): array
    {

        $agent = AgentStatistics::where(['user_id' => $this->user['id']])->find();
        if (empty($agent)) {
            $apply = AgentApply::where('user_id', $this->user['id'])->find();
            if (!empty($apply)) {
                if ($apply['status'] == 0)
                    return [HTTP_SUCCESS, ['type' => 1]];
                if ($apply['status'] == 2)
                    return [HTTP_SUCCESS, ['type' => 2]];
            }
        }
        if (!empty($agent->grade_id)) {
            $agent->grade = AgentGrade::find($agent->grade_id);
        }
        list($code,$data) = $this->agent_order(1,10,[]);

        $agent->count_order=$data['total']??0;
        $agent->team=$this->getTeam();

        return [HTTP_SUCCESS, $agent];
    }


    public function agent_order(int $page, int $size, array $data): array
    {

        $where = [];
        $user_id = $this->user['id'];
        (isset($data['status']) && $data['status'] != -1) && $where[] = ['abt.status', '=', $data['status']];
        !empty($data['start_time']) && $where[] = ['abt.create_time', '>=', $data['start_time']];
        !empty($data['end_time']) && $where[] = ['abt.end_time', '<=', $data['end_time']];
        $billList = AgentBillTemporary::field('abt.id,abt.is_self,abt.agent_id,abt.status,abt.source_user_id,abt.steps,abt.uniqid,abt.order_no,abt.commodity_id')
            ->alias('abt')
            ->hidden(['uniqid'])
            ->join('order o', 'o.id = abt.order_id', 'LEFT')
            ->where($where)
            ->where('agent_id', 'in', function (Query $query) use ($user_id) {
                $query->name('agent')->field('id')->where('user_id', $user_id);
            })
            ->whereRaw('(abt.steps=0 AND abt.is_self=1) or (abt.is_self=0)')
            ->where('o.status', '>', 1)
            ->where('o.status', '<', 12)
            ->where('abt.status', '<>', 2)
            ->with(['orderAgentProfit', 'commodityNameMaster', 'sourceUserNicknamePicurl'])
            ->order('abt.create_time DESC')
            ->append(['status_text'])
            ->paginate(['page' => $page, 'list_rows' => $size])
            ->toArray();

        $user = AgentBillTemporary::stepsAgent($billList['data']);
        foreach ($billList['data'] AS $key => $value) {
            for ($i = 1; $i < 4; $i++) {
                if (empty($value['agent' . $i]))
                    unset($billList['data'][$key]['agent' . $i]);
                else
                    $billList['data'][$key]['agent' . $i] = $user[$value['agent' . $i]];
            }
        }
        return [HTTP_SUCCESS, $billList];
    }

    public function agentGrade()
    {
        $mid = $this->user['mall_id'] ? $this->user['mall_id'] : request()->header('mid', 0);
        $grades = AgentGrade::where("mall_id", $mid)
            ->where('status', 1)
            ->order('id')
            ->select();
        $agent = Agent::where(['user_id' => $this->user['id']])->find();
        // 下级用户人数
        $current_users = Agent::getUsers($agent['id'], $mid);
        // 佣金总额
        $current_commission = Agent::getCommissions($agent['id'], $mid);

        // 已提现佣金总额
        $current_draw = Agent::getDraw($agent['user_id'], $agent['id'], $mid);

        $current_payment = Agent::getPayment($agent['id'], $mid);

        // 下级分销商人数
        $current_agents = Agent::getAgents($agent['id'], $mid);
        foreach ($grades as $key => &$grade) {
            $grade['current_users'] = $current_users;
            $grade['current_commission'] = $current_commission;
            $grade['current_draw'] = $current_draw;
            $grade['current_payment'] = $current_payment;
            $grade['current_agents'] = $current_agents;
        }
        return [HTTP_SUCCESS, $grades];
    }

    public function ActivityList(int $page = 1, int $size = 10)
    {


        $status = request()->get('status');

        $agent = $this->agent;

        $where = ['mall_id' => $agent->mall_id];
        if (is_numeric($status))
            $where['status'] = $status;

        $list = CommissionActivity::where($where)
            ->paginate(['page' => $page, 'list_rows' => $size]);
        $new_list = [];

        foreach ($list as $item => $value) {
            if ($value->level_type == 1) {
                $levels = json_decode($value->levels, true);
                if (in_array($agent->grade_id, $levels)) {
                    array_push($new_list, $value);
                }
            } else {
                array_push($new_list, $value);
            }

        }

        return [HTTP_SUCCESS, $new_list];
    }

    public function ActivityInfo($id)
    {


        # $id=request()->get('id');
//        $time = date("Y-m-d H:i:s");
//        $where = [
//            ['start_time', '<', $time],
//            ['end_time', '>', $time],
//            ['status', '=', 1]
//        ];

        $where = ['id' => $id];
        $activity = CommissionActivity::where($where)->find();
        if (!$activity) {
            return [HTTP_NOTACCEPT, "暂无活动"];
            #return json(['msg' => "暂无活动"],HTTP_NOTACCEPT);
        }
        $level_type = $activity->level_type;
        $AgentGrades = [];
        if ($level_type == 1) {
            $levels = json_decode($activity->levels, true);
            if (!empty($levels)) {
                $AgentGrades = AgentGrade::where('id', 'in', $levels)->field('id,name')->select();
            }
        } else {
            $AgentGrades = AgentGrade::where([])->field('id,name')->select();
        }


        $where = [["create_time", ">", $activity->start_time], ["create_time", "<", $activity->end_time], ["mall_id", '=', $activity->mall_id]];
        $award_role = \app\madmin\model\CommissionActivity::getAwardRole($activity);

        #规则总数
        $role_count = count($award_role);

        $agent = $this->agent;


        $arr = [0 => 'first', 1 => 'second', 2 => 'third'];

        $list = [];

        foreach ($award_role as $item => $value) {
            $item = $arr[$item];

            $list['step'][$item]['child_count_success'] = 0;
            $list['step'][$item]['order_count_success'] = 0;
            $list['step'][$item]['order_money_success'] = 0;
            $list['step'][$item]['child_agent_count_success'] = 0;
            // 下级用户人数
            $user_count = \app\madmin\model\CommissionActivity::getUsers($agent['id'], $where);
            //销售额
            $payment = \app\madmin\model\CommissionActivity::getPayment($agent['id'], $where);
            //下级分销商数
            $agents_count = \app\madmin\model\CommissionActivity::getAgents($agent['id'], $where);
            //下级订单总数
            $order_count = \app\madmin\model\CommissionActivity::getOrderCount($agent['id'], $where);
            $list['step'][$item]['user_count'] = $user_count;
            $list['step'][$item]['pay_ment'] = $payment;
            $list['step'][$item]['agent_count'] = $agents_count;
            $list['step'][$item]['order_count'] = $order_count;
            $d['agent'] = $agent->toArray();
            $d['award_role'] = $award_role;

            #从高到底去奖励
            for ($i = $role_count - 1; $i >= 0; $i--) {
                if (!isset($award_role[$i])) {
                    break;
                }
                $role_info = $award_role[$i];
                $award = $role_info['award'] ?? [];
                if (isset($award['coupon'])) {
                    if (is_array($award['coupon'])) {
                        $role_info['coupons'] = Coupon::where('id', 'in', $award['coupon'])->hidden(['create_time', 'update_time', 'delete_time', 'status', 'used', 'is_show', 'audit', 'audit_remark', 'sort', 'use_limit_type'])->select()->toArray();
                    }
                }

                $condition = $role_info['condition'];
                if (!empty($condition['child_count'])) {
                    $list['step'][$item]['child_count_success'] = $user_count >= $condition['child_count'] ? 1 : 0;
                    $condition['info']['child_count_success'] = $user_count >= $condition['child_count'] ? 1 : 0;
                    $condition['info']['user_count'] = $user_count;
                }
                if (!empty($condition['order_count'])) {
                    $list['step'][$item]['order_count_success'] = $order_count >= $condition['order_count'] ? 1 : 0;
                    $condition['info']['order_count_success'] = $order_count >= $condition['order_count'] ? 1 : 0;
                    $condition['info']['order_count'] = $order_count;
                }
                if (!empty($condition['order_money'])) {
                    $list['step'][$item]['order_money_success'] = $payment >= $condition['order_money'] ? 1 : 0;
                    $condition['info']['order_money_success'] = $payment >= $condition['order_money'] ? 1 : 0;
                    $condition['info']['pay_ment'] = $payment;
                }
                if (!empty($condition['child_agent_count'])) {
                    $list['step'][$item]['child_agent_count_success'] = $agents_count >= $condition['child_agent_count'] ? 1 : 0;
                    $condition['info']['child_agent_count_success'] = $agents_count >= $condition['child_agent_count'] ? 1 : 0;
                    $condition['info']['agent_count'] = $agents_count;

                }
                $list['step'][$item]['condition'] = $condition;
                $list['step'][$item]['role_info'] = $role_info;
            }
            $debugs[] = $d;
        }
        $list['activity'] = $activity;
        $list['agent'] = $agent;
        $list['agentGrades'] = $AgentGrades;
        return [HTTP_SUCCESS, $list];
//        return json(['msg' => $list],HTTP_SUCCESS);
    }

    public function AssessmentInfo()
    {


        $time = date("Y-m-d H:i:s");
        $where = [
            ['start_time', '<', $time],
            ['end_time', '>', $time],
            ['status', '=', 1]
        ];
        $assessment = CommissionAssessment::where($where)->find();

//        if (!$assessment){
//            return [HTTP_NOTACCEPT,"暂无考核活动"];
//        }
        $agent = $this->agent;
        $agent_grade = AgentGrade::find($agent->grade_id);
        if ($assessment) {
            $where = [["create_time", ">", $assessment->start_time], ["create_time", "<", $assessment->end_time], ["mall_id", '=', $assessment->mall_id], ["agent_id", '=', $agent->id]];

            $assessment_type = $assessment->assessment_type;

            if ($assessment_type == 0) {
                $assessment_value = \app\madmin\model\CommissionAssessment::getPayment($where);
            } else {
                $assessment_value = \app\madmin\model\CommissionAssessment::getOrderCount($where);
            }

            $role_data = json_decode($assessment->role, true);


            $agent_level = $agent->grade_id;

            $steps = [];
            #$arr=[0=>'first',1=>'second',2=>'third'];

            foreach ($role_data as $k => $role_info) {
                if ($role_info['level'] == $agent_level) {
                    $role = $role_info['rule'];
                    $role_count = count($role);

                    for ($i = 0; $i < $role_count; $i++) {
                        if ($role[$i]['max'] == -1) {
                            $is_success = $assessment_value > $role[$i]['min'] ? 1 : 0;
                        } else {
                            $is_success = $assessment_value > $role[$i]['max'] ? 1 : 0;
                        }
                        $steps[$i] = ['commission_rate' => $role[$i]['ladder_commission_rate'], 'assessment_type' => $assessment_type, 'assessment_value' => $assessment_value, 'assessment_success_value' => $role[$i]['min'], 'min' => $role[$i]['min'], 'is_success' => $is_success];
                    }
                }
            }
        }

        $user_cash = UserCash::where(['user_id' => $agent->user_id])->field('assessment,assessment_total,assessment_withdraw')->find()->toArray();

        $list['agent'] = $agent;
        $list['commission_info'] = $user_cash;
        $list['agent_grade'] = $agent_grade;
        $list['steps'] = $steps ?? [];
        $list['assessment'] = $assessment ?? [];

        return [HTTP_SUCCESS, $list];
        return json(['msg' => $list], HTTP_SUCCESS);
    }

    public function getTeam(){

        $configuration = new ConfigurationService();
        list($code,$msg)=$configuration->read('agentExplain');
        $level= $msg['level'] ?? 3;

        #$user_num=\app\madmin\model\CommissionActivity::getUsers($this->agent->id,[]);

        $first_count=AgentTeam::where(array('pid' => $this->agent->id))->count() ?? 0;
        $second_count= AgentTeam::where(array('ppid' => $this->agent->id))->count() ?? 0;
        $third_count=AgentTeam::where(array('pppid' => $this->agent->id))->count() ?? 0;
        #$team_count=$user_num+$first_count+$second_count+$third_count;
        if($level == 1) {
            return $first_count;
        }elseif ($level ==2 ){
            return $first_count+ $second_count;
        }else{
            return $first_count+$second_count+$third_count;
        }
    }
}